<template>
  <div class="bg-white sticky top-0 left-0 z-10 duration-500">
    <ul
      ref="ulTarget"
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
    >
      <!-- 滑块 -->
      <li
        ref="sliderTarget"
        :style="sliderStyle"
        class="absolute h-[22px] dark:bg-zinc-800 bg-zinc-900 rounded-lg duration-200"
      ></li>
      <!-- 汉堡按钮 -->
      <li
        @click="onShowProup"
        class="fixed top-0 right-[-1px] h-4 px-1 flex items-center dark:bg-zinc-900 bg-white z-20 dark:shadow-l-zinc shadow-l-white"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="hamburger"></m-svg-icon>
      </li>
      <!-- items -->
      <li
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
        v-for="(item, index) of $store.getters.categorys"
        :key="item.id"
        :ref="setItemRef"
        @click="onItemClick(item)"
        :class="{
          ' text-zinc-100': $store.getters.currentCategoryIndex === index
        }"
      >
        {{ item.name }}
      </li>
    </ul>
  </div>
  <m-popup v-model="isVisiable">
    <menu-vue @onItemClick="onItemClick"></menu-vue>
  </m-popup>
</template>

<script setup>
import { ref } from '@vue/reactivity'
import { onBeforeUpdate, watch } from '@vue/runtime-core'
import { useScroll } from '@vueuse/core'
import MenuVue from '@/views/main/components/menu/index.vue'
import { useStore } from 'vuex'

const store = useStore()

// 给sliderStyle样式
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '54px'
})

// 获取所有Item元素
let itemRefs = []
const setItemRef = (el) => {
  itemRefs.push(el)
}

// 数据改变之后Dom更新之前
onBeforeUpdate(() => {
  itemRefs = []
})

// 获取ul元素
const ulTarget = ref(null)

// 通过vueuse -> useScroll 获取响应式的scroll 滚动距离
const { x: ulScrollLeft } = useScroll(ulTarget)

// watch 监听
watch(
  () => store.getters.currentCategoryIndex,
  (val) => {
    const { width, left } = itemRefs[val].getBoundingClientRect()
    const scollX = ulScrollLeft.value + left
    sliderStyle.value = {
      width: width + 'px',
      transform: `translateX(${scollX - 10}px)`
    }
  }
)

// 弹出框的v-model
const isVisiable = ref(false)

// 点击item
const onItemClick = (item) => {
  store.commit('app/changeCurrentCategory', item)
  isVisiable.value = false
}

// 汉堡按钮点击
const onShowProup = () => {
  isVisiable.value = true
}
</script>
